<!-- /src/components/BucketContents/ObjectBatchActionBar.vue (最终修正版) -->

<template>
    <div>
        <!-- 1. 原生底部栏 -->
        <div class="bottom-action-bar" ref="bottomActionBarRef">
            <div class="batch-actions-left">
                <el-checkbox :model-value="isAllSelected" :indeterminate="isIndeterminate" @change="onSelectAllChange"
                    :disabled="totalItems === 0" />
                <!-- 【修改】将批量操作按钮分组 -->
                <div class="button-group">
                    <el-button v-if="!showVersions" @click="openMetadataDrawer"
                        :disabled="!canSetMetadata">设置元数据</el-button>
                    <el-button @click="openExportUrlDrawer" :disabled="!canExportUrl">导出URL列表</el-button>
                    <el-button v-if="!showVersions" :disabled="selectedCount === 0" @click="handleBatchDownload"
                        :loading="isDownloading">下载</el-button>
                    <el-button :disabled="selectedCount === 0" @click="$emit('batch-delete')">
                        {{ showVersions ? '彻底删除' : '删除' }}
                    </el-button>
                    <!-- 【新增】批量恢复按钮，用 v-if 控制显示 -->
                    <el-button v-if="showVersions && isVersioningEnabled" :disabled="!canBatchRestore"
                        @click="$emit('batch-restore')">恢复</el-button>
                </div>
                <span v-if="selectedCount > 0 && !showVersions">已选择：{{ selectedCount }} / {{ totalItems }}</span>
            </div>
            <el-pagination v-model:current-page="internalCurrentPage" v-model:page-size="internalPageSize"
                :page-sizes="[50, 100, 200, 500]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total" @size-change="onSizeChange" @current-change="onCurrentChange" />
        </div>

        <!-- 2. 悬浮的底部操作栏 -->
        <Transition name="fade">
            <div class="floating-action-bar" v-if="isFloatingBarVisible" ref="floatingBarRef">
                <div class="batch-actions-left">
                    <el-checkbox :model-value="isAllSelected" :indeterminate="isIndeterminate"
                        @change="onSelectAllChange" :disabled="totalItems === 0" />
                    <div class="button-group">
                        <el-button v-if="!showVersions" @click="openMetadataDrawer"
                            :disabled="!canSetMetadata">设置元数据</el-button>
                        <el-button @click="openExportUrlDrawer" :disabled="!canExportUrl">导出URL列表</el-button>
                        <el-button v-if="!showVersions" :disabled="selectedCount === 0" @click="handleBatchDownload"
                            :loading="isDownloading">下载</el-button>
                        <el-button :disabled="selectedCount === 0" @click="$emit('batch-delete')">
                            {{ showVersions ? '彻底删除' : '删除' }}
                        </el-button>
                        <!-- 【新增】批量恢复按钮，用 v-if 控制显示 -->
                        <el-button v-if="showVersions && isVersioningEnabled" :disabled="!canBatchRestore"
                            @click="$emit('batch-restore')">恢复</el-button>
                    </div>
                    <span v-if="selectedCount > 0 && !showVersions">已选择：{{ selectedCount }} / {{ totalItems }}</span>
                </div>
                <el-pagination v-model:current-page="internalCurrentPage" v-model:page-size="internalPageSize"
                    :page-sizes="[50, 100, 200, 500]" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                    @size-change="onSizeChange" @current-change="onCurrentChange" />
            </div>
        </Transition>
    </div>

    <SetObjectMetadataDrawer v-if="metadataDrawerVisible" v-model="metadataDrawerVisible" :bucket-name="bucketName"
        mode="batch" :selected-items="selectedItems" @success="$emit('action-completed')" />

    <ExportUrlDrawer v-if="exportUrlDrawerVisible" v-model="exportUrlDrawerVisible" :bucket-name="bucketName"
        :selected-items="selectedItems" />
</template>

<script setup>
import { ref, computed, watch, onUnmounted, nextTick } from 'vue'; // 移除了 onMounted
import { useElementVisibility } from '@vueuse/core';
import { useLayoutStore } from '@/stores';
import { secureBatchDownload } from '@/utils/downloadHelper';
import SetObjectMetadataDrawer from '@/components/SetObjectMetadataDrawer.vue';
import ExportUrlDrawer from '@/components/ExportUrlDrawer.vue';
import { useRoute } from 'vue-router'; // 1. 【新增】导入 useRoute
import apiClient from '@/api';         // 2. 【新增】导入 apiClient
import { ElMessage } from 'element-plus'; // 3. 【新增】导入 ElMessage
import { saveAs } from 'file-saver';    // 4. 【新增】导入 saveAs

const route = useRoute(); // 5. 【新增】获取当前路由信息实例

// --- 1. Props & Emits ---
const props = defineProps({
    selectedItems: { type: Array, default: () => [] }, // 【修改】直接接收选中的完整对象列表
    totalItems: { type: Number, required: true },
    isAllSelected: { type: Boolean, default: false },
    isIndeterminate: { type: Boolean, default: false },
    pagination: { type: Object, required: true },
    isDownloading: { type: Boolean, default: false },
    tableEl: { type: Object, default: null },
    isVersioningEnabled: { type: Boolean, default: false }, // 【新增】接收版本控制状态
    showVersions: { type: Boolean, default: false },
    bucketName: { type: String, required: true } // 接收 bucketName
});

const emit = defineEmits(['select-all-change', 'batch-delete', 'batch-restore', 'size-change', 'current-change']);

const metadataDrawerVisible = ref(false);
const exportUrlDrawerVisible = ref(false);

const openMetadataDrawer = () => {
    metadataDrawerVisible.value = true;
};

const openExportUrlDrawer = () => {
    exportUrlDrawerVisible.value = true;
};

const canSetMetadata = computed(() => {
    if (props.selectedItems.length === 0) return false;
    // 只有文件才能设置元数据
    return props.selectedItems.every(item => item.type === 'file');
});

const canExportUrl = computed(() => {
    // 只要有选中项，就可以导出URL
    return props.selectedItems.length > 0;
})

// --- 2. 内部状态和计算属性 ---
const selectedCount = computed(() => props.selectedItems.length);
const isDownloading = ref(false); // 【新增】下载状态由组件自己管理
// const isIndeterminate = computed(() => props.selectedCount > 0 && props.selectedCount < props.totalItems);
// const isAllSelected = computed(() => props.totalItems > 0 && props.selectedCount === props.totalItems);

// 【新增】计算属性，判断“批量恢复”按钮是否可用
const canBatchRestore = computed(() => {
    if (!props.isVersioningEnabled || selectedCount.value === 0) {
        return false;
    }
    // every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试
    return props.selectedItems.every(item =>
        item.type === 'file' && !item.is_latest
    );
});

// const handleBatchDownload = async () => {
//     isDownloading.value = true;
//     try {
//         // 直接调用下载助手，使用 props 传入的数据
//         await secureBatchDownload(props.bucketName, props.selectedItems);
//     } finally {
//         isDownloading.value = false;
//     }
// };

const handleBatchDownload = async () => {
    // 【修正1】直接从 props 获取选中的文件/文件夹对象列表
    const selectedItems = props.selectedItems;
    if (!selectedItems || selectedItems.length === 0) {
        ElMessage.warning('请至少选择一个项目进行下载');
        return;
    }

    // 【修正2】提取所有选中项的 key
    const selectedKeys = selectedItems.map(item => item.name);

    // ================== 【核心逻辑判断】 ==================
    // 假设存放日志的桶名包含 'log' 或 'logging' 关键字
    // 这是一个简单但有效的判断方式
    const isLoggingBucket = route.params.bucketName.toLowerCase().includes('log');

    // **【优化】** 一个更精确的判断：如果当前路由是日志查询页，那么一定是下载日志
    const isInLogViewerPage = route.name === 'BucketLogViewer';

    // **【最终决策】** 优先使用路由名称判断，如果失败再用桶名判断作为后备
    if (isInLogViewerPage || isLoggingBucket) {
        // **场景A: 在日志桶中，调用新的后端打包API**
        isDownloading.value = true;
        try {
            const response = await apiClient.post(
                `/api/v1/buckets/${props.bucketName}/logs/batch-download`,
                { keys: selectedKeys },
                { responseType: 'blob' }
            );

            const blob = new Blob([response.data], { type: 'application/zip' });

            const contentDisposition = response.headers['content-disposition'];
            let filename = `${props.bucketName}-logs.zip`;
            if (contentDisposition) {
                // 【修正3】使用更健壮的正则表达式来解析文件名
                const filenameMatch = contentDisposition.match(/filename\*?=(?:UTF-8'')?([^;]+)/);
                if (filenameMatch && filenameMatch[1]) {
                    try {
                        filename = decodeURIComponent(filenameMatch[1].replace(/"/g, ''));
                    } catch (e) {
                        console.warn("解码文件名失败，使用默认名称", e);
                    }
                }
            }
            saveAs(blob, filename);

        } catch (error) {
            console.error('批量下载日志失败:', error);
            ElMessage.error('批量下载日志失败，请查看控制台');
        } finally {
            isDownloading.value = false;
        }

    } else {
        // **场景B: 在普通数据桶中，还走原来的前端打包逻辑**
        // 【修正4】这里的 isDownloading 状态也需要管理
        isDownloading.value = true;
        try {
            // 直接调用下载助手，参数正确
            await secureBatchDownload(props.bucketName, selectedItems);
        } finally {
            isDownloading.value = false;
        }
    }
    // =======================================================
};

// 使用内部 ref 代理分页器的 v-model，避免直接修改 prop
const internalCurrentPage = ref(props.pagination.currentPage);
const internalPageSize = ref(props.pagination.pageSize);

watch(() => props.pagination.currentPage, (val) => { internalCurrentPage.value = val; });
watch(() => props.pagination.pageSize, (val) => { internalPageSize.value = val; });

// --- 3. 事件处理函数 (只是向上 emit) ---
const onSelectAllChange = (checked) => emit('select-all-change', checked);
const onSizeChange = (size) => emit('size-change', size);
const onCurrentChange = (page) => emit('current-change', page);

// --- 4. 悬浮操作栏的完整逻辑 ---
const floatingBarRef = ref(null);
const bottomActionBarRef = ref(null);
const isBottomActionBarVisible = useElementVisibility(bottomActionBarRef);
const isFloatingBarVisible = ref(false);
const layoutStore = useLayoutStore();

let animationFrameId = null;

const updateFloatingBarPosition = () => {
    const tableEl = props.tableEl;
    const floatingBar = floatingBarRef.value;
    if (!tableEl || !floatingBar || typeof tableEl.getBoundingClientRect !== 'function') {
        // 如果 tableEl 不存在，或者它没有 getBoundingClientRect 这个方法，
        // 就直接返回，什么也不做。
        return;
    }
    const rect = tableEl.getBoundingClientRect();
    const offset = 20;
    floatingBar.style.left = `${rect.left - offset}px`;
};

const animateFloatingBar = () => {
    updateFloatingBarPosition();
    animationFrameId = requestAnimationFrame(animateFloatingBar);
};

const startAnimation = () => {
    stopAnimation();
    animationFrameId = requestAnimationFrame(animateFloatingBar);
};

const stopAnimation = () => {
    if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
        animationFrameId = null;
    }
};

watch(isBottomActionBarVisible, (isVisible) => {
    isFloatingBarVisible.value = props.totalItems > 0 && !isVisible;
    if (isFloatingBarVisible.value) {
        nextTick(() => updateFloatingBarPosition());
    }
});

watch(() => layoutStore.isSidebarCollapsed, () => {
    startAnimation();
    setTimeout(stopAnimation, 350);
});

onUnmounted(() => {
    stopAnimation();
});
</script>

<style scoped>
/* 原生底部栏容器 */
.bottom-action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding: 8px 0 8px 12px;
}

/* 悬浮底部栏 */
.floating-action-bar {
    position: fixed;
    bottom: 0;
    right: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px 10px 32px;
    background-color: #ffffff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.08);
    border-top: 1px solid #ebeef5;
    z-index: 100;
    box-sizing: border-box;
}

/* 左侧批量操作按钮区域，共用样式 */
.batch-actions-left {
    display: flex;
    align-items: center;
    gap: 16px;
}

/* 【新增】按钮组样式 */
.button-group {
    display: flex;
    gap: 10px;
}

.batch-actions-left span {
    font-size: 14px;
    color: #606266;
}

/* 悬浮栏淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>